﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml.Linq;

namespace MotionControl.Modules.PLC.Business
{
    public class FloatList : ObservableCollection<FloatType>
    {
        public static FloatList GetInstance { get => _instance.Value; }

        private static readonly Lazy<FloatList> _instance = new Lazy<FloatList>(() => new FloatList(), true);
        private FloatList() {
            Add(new FloatType("进料皮带轴速度", "mm/s"));
            Add(new FloatType("出料皮带轴速度", "mm/s"));
            Add(new FloatType("上吸附皮带轴速度", "mm/s"));
            Add(new FloatType("上相机轴速度", "mm/s"));
            Add(new FloatType("下相机轴速度", "mm/s"));
            Add(new FloatType("上吸附皮带升降轴速度", "mm/s"));
            Add(new FloatType("光源升降轴速度", "mm/s"));
            Add(new FloatType("皮带自动运行速度", "mm/s"));
            Add(new FloatType("皮带返回速度", "mm/s"));
            Add(new FloatType("PCB板长度", "mm"));
            Add(new FloatType("PCB板厚度", "mm"));
            Add(new FloatType("上相机基准位置", "mm"));
            Add(new FloatType("下相机基准位置", "mm"));
            Add(new FloatType("上吸附升降行程", "mm"));
            Add(new FloatType("挡停至光源距离", "mm"));
            Add(new FloatType("分频脉冲数", "plus"));
            Add(new FloatType("相机触发延时", "ms"));
            Add(new FloatType("挡停抬起延时", "ms"));

            ReadFromJsonFile();
        }

        private const string jsonFilePath = "data/plc_floats.json";
        public void ReadFromJsonFile()
        {
            try
            {
                string jsonFromFile = File.ReadAllText(jsonFilePath);
                var deserializedList = JsonConvert.DeserializeObject<List<FloatType>>(jsonFromFile);
                for(int i = 0; i < Items.Count; i++) 
                {
                    Items[i].FloatValue = deserializedList[i].FloatValue;
                }
            }
            catch (Exception ex) { 
            }
        }

        public void SaveToJsonFile()
        {
            try
            {        
                JsonSerializer serializer = new JsonSerializer();
                string strFloats = JsonConvert.SerializeObject(this.ToList(),Formatting.Indented);
                File.WriteAllText(jsonFilePath, strFloats);               
            }
            catch (Exception ex)
            {

            }
        }
        public void RegisterAction(Action<string, float> act)
        {
            foreach (var item in Items)
            {
                item.floatTypeAction += act;
                act.Invoke(item.Name, item.FloatValue);
                item.saveAction += SaveToJsonFile;
            }            
        }
    }
}
